// app.js
const express = require("express");
const cors = require("cors");

// 路由
const authRoutes = require("./routes/auth");
const merchantsRoutes = require("./routes/merchants");
const productsRoutes = require("./routes/products");
const customersRoutes = require("./routes/customers");
const ordersRoutes = require("./routes/orders");
const adsRoutes = require("./routes/ads");
const rulesRoutes = require("./routes/rules");
const activitiesRoutes = require("./routes/activities");
const prizesRoutes = require("./routes/prizes");
const cashRoutes = require("./routes/cash");
const distributionRoutes = require("./routes/distribution");

const app = express();

/* 1. 放大 JSON 限制（Base64 图片可能 1~2 MB） */
app.use(express.json({ limit: "5mb" })); // ← 关键
app.use(express.urlencoded({ extended: true, limit: "5mb" }));

// 中间件
app.use(cors());
app.use(express.json()); // 解析 JSON
app.use(express.urlencoded({ extended: true })); // 解析 URL-encoded 数据

// 路由挂载，统一前缀 /api
app.use("/auth", authRoutes);
app.use("/merchants", merchantsRoutes);
app.use("/products", productsRoutes);
app.use("/customers", customersRoutes);
app.use("/orders", ordersRoutes);
app.use("/ads", adsRoutes);
app.use("/rules", rulesRoutes);
app.use("/activities", activitiesRoutes);
app.use("/prizes", prizesRoutes);
app.use("/cash", cashRoutes);
app.use("/distribution", distributionRoutes);

// 根路径测试
app.get("/", (req, res) => {
  res.send("Backend is running!");
});

// 统一错误处理（可选）
app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).json({ message: "服务器内部错误" });
});

// 启动服务
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server running on http://localhost:${PORT}`);
});
